'''
Created on 19 dec. 2011

@author: Daan
'''
import math

from Roads.Road import Road

class Turn(Road):
    '''
    classdocs
    '''
    def __init__(self, lanes, x, y, length, opposite, name):
        '''
        Constructor
        '''
        Road.__init__(self, lanes, x, y, length, opposite, name)
        
        self.laneLines = []
        for x in range(lanes): self.laneLines.append(None)

    def GetX(self):
        return self._x + self._l / 2
    
    def GetY(self):
        return self._y
    
    def GetL(self):
        return self._l / 2

    def GetXYInLane(self, lane, offset, canvas=None):
        offsetFromCenter = self.GetLaneCenter(lane, offset)
        length = self.GetLength(lane)
        
        cxy = (self.GetX(), self.GetY() + self.GetL())
        
        xdegree = ((180 * offset) / length) - 90
        ydegree = 180 - xdegree
        
        try:
            x = math.cos(math.radians(xdegree)) * offsetFromCenter
            y = math.sin(math.radians(ydegree)) * offsetFromCenter
            
            if self._opposite:
                return (cxy[0] + x, cxy[1] + y)
            return (cxy[0] - x, cxy[1] - y)
        except (ValueError,), ex:
            print "Exception: %s" % ex 
            return (0, 0)
    
    def GetLaneCenter(self, lane, offset):
        base = math.ceil(Road.width / 2)
        
        remainder = ((self.GetL() * 2) - (Road.CalcHeight(self._lanes) * 2)) / 2
        
        length = remainder + base + ((lane - 1) * Road.width)
        return length
    
    def Draw(self, canvas):
        line = 0
        lines = self._lanes + 1
        start = 270 if self._opposite else 90
        width = Road.CalcHeight(self._lanes)
        
        while line < lines :
            offset = Road.width * line
            
            x1 = self._x + offset
            y1 = self._y + offset
            x2 = x1 + self._l - offset * 2
            y2 = y1 + self._l - offset * 2
            
            canvas.create_arc((x1, y1, x2, y2), fill="gray", outline="red", start=start, extent=180)
            line += 1
        
        x1 = self._x + width + 1
        y1 = self._y + width + 1
        x2 = x1 + (self._l - (width * 2)) - 2 
        y2 = y1 + (self._l - (width * 2)) - 2
        canvas.create_arc((x1, y1, x2, y2), fill="white", outline="", start=start, extent=180)
        
        cxy = (self.GetX(), self.GetY() + self.GetL())
